import axios from 'axios'
import qs from "qs"
import {chooseDomain} from "@/config/env"
  const axiosInstance=axios.create({
    baseURL:chooseDomain(),
    timeout:5000
  })

  axiosInstance.interceptors.request.use(
    (config) => {
      const token = "";
      const mConfig = config;
      if (token !== "") {
        mConfig.headers = {
          authorization: token,
        };
      }
      return mConfig;
    },
    (error) => Promise.reject(error),
  );
  
  // 响应拦截器
  axiosInstance.interceptors.response.use(
    (res) => res,
    (error) => Promise.reject(error),
  );
  
  export function successAction(res, url) {
    // 打印结果
    return res.data;
  }
  //error
  export function errorAction(error, url) {
    const res = error.response;
    // 打印结果
    const result = {
      result: res.status,
      message: "",
    };
    return result;
  }
  /**
 * get请求格式化参数
 */
function setUrlWithParams(url, data) {
  let link = url;
  if (data && !_.isEmpty(data)) {
    const formatData = qs.stringify(data);
    link = `${url}?${formatData}`;
    return link;
  }
  return link;
}

  /**
   * get方法
   * @param url
   * @param params
   */
  function get(url, params) {
    // 请求路径添加处理参数
    const path = setUrlWithParams(url, params);
    // 请求实例
    return axiosInstance
      .get(path)
      .then((res) => successAction(res, url))
      .catch((error) => errorAction(error, url));
  }
  
  /**
   * POST方法
   * @param url
   * @param params
   */
  function post(url, params){
    // 请求实例
    return axiosInstance
      .post(url, params)
      .then((res) => successAction(res, url))
      .catch((error) => errorAction(error, url));
  }


  export function open(api, params) {
    // 根据api信息确定请求格式
    if (api.method === "POST") {
      return post(api.url, params);
    }
    // 默认用get方式
    return link.get(api.url,params);
  }
  export default {
    open
  };